<template>
  <div class="app-container">
    <el-form
      ref="queryParams"
      :model="queryParams"
      size="small"
      label-position="right"
      label-suffix=":"
      label-width="120px"
    >
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item>
            <template #label>
              <el-select v-model="statusType">
                <!--                <el-option :value="0" :label="$t('statusLang.orderStatus')" />-->
                <el-option
                  :value="1"
                  :label="$t('statusLang.outboundStatus')"
                />
              </el-select>
            </template>
            <el-radio-group
              v-if="statusType === 0"
              v-model="queryParams.orderStatus"
            >
              <el-radio-button>{{ $t("all") }}</el-radio-button>
              <el-radio-button
                v-for="item in orderStatusOptions"
                :key="item.key"
                :label="item.value"
              >
                {{ $t("statusLang." + item.title) }}
              </el-radio-button>
            </el-radio-group>
            <el-radio-group v-else v-model="queryParams.orderStatus">
              <el-radio-button>{{ $t("all") }}</el-radio-button>
              <el-radio-button
                v-for="item in depotOperationStatusOptions"
                :key="item.key"
                :label="item.value"
              >
                {{ $t("statusLang." + item.title) }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item>
            <template #label>
              <el-select v-model="noType">
                <el-option
                  :value="0"
                  :label="$t('outboundOrderLang.warehouseOutDocNo')"
                />
                <el-option
                  :value="3"
                  :label="$t('outboundOrderLang.trackingNo')"
                />
                <el-option
                  :value="1"
                  :label="$t('outboundOrderLang.siCode')"
                />
                <el-option
                  :value="2"
                  :label="$t('outboundOrderLang.providerNo')"
                />
              </el-select>
            </template>
            <el-input
              v-model="anyNo"
              type="textarea"
              :rows="3"
              style="width: 350px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item :label="$t('depotLang.depot')">
            <el-select
              v-model="queryParams.depotId"
              style="width: 350px"
              clearable
            >
              <el-option
                v-for="item in depotOptions"
                :key="item.value"
                :label="item.title"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item>
            <template #label>
              <el-select v-model="timeType">
                <el-option :value="0" :label="$t('orderDate')" />
                <el-option :value="1" :label="$t('outboundDate')" />
                <el-option :value="2" :label="$t('receivedDate')" />
              </el-select>
            </template>
            <el-date-picker
              v-model="timeRange"
              type="daterange"
              value-format="timestamp"
              :start-placeholder="$t('beginDate')"
              :range-separator="$t('to')"
              :end-placeholder="$t('endDate')"
              style="width: 350px"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item :label="$t('harvestLang.providerChannel')" prop="channelName">
            <el-select v-model="queryParams.providerChannelId">
              <el-option
                v-for="channel in provideChannelList"
                :key="channel.channelId"
                :label="channel.channelName"
                :value="channel.channelId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item
            :label="$t('harvestLang.customerName')"
            prop="customerId"
          >
            <el-select
              v-model="queryParams.customerId"
              :placeholder="$t('pleaseSelect')"
              clearable
              filterable
              style="width: 200px"
            >
              <el-option
                v-for="item in customerOptionList"
                :key="item.value"
                :value="item.value"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="1.5">
          <el-form-item
            :label="$t('goodsSKULang.skuCode')"
            prop="skuCode"
          >
            <el-input
              v-model="queryParams.skuCode"
              :placeholder="$t('goodsSKULang.skuCode')"
              clearable
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="handleQuery"
          >
            {{ $t("query") }}
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-refresh-left"
            @click="handleReset"
          >
            {{ $t("reset") }}
          </el-button>
          <el-button type="primary" size="small" icon="el-icon-download" @click="exportToExcel()">
            {{ $t("goodsSKULang.imports") }}
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-table ref="table" v-loading="loading" :data="data">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        type="index"
        :label="$t('tableIndex')"
        width="55px"
        align="center"
        fixed="left"
      />
      <el-table-column
        :label="$t('harvestLang.orderInfo')"
        min-width="200px"
        align="center"
      >
        <template slot-scope="scope">
          <div>
            {{ $t("outboundOrderLang.warehouseOutDocNo") + " : "
            }}{{ scope.row.orderNo }}
          </div>
          <div>
            {{ $t("outboundOrderLang.trackingNo") + " : "
            }}{{ scope.row.trackingNo }}
          </div>
          <div>
            {{ $t("goodsSKULang.dataSources") + " : " }}{{ scope.row.source }}
          </div>
          <div>
            {{ $t("outboundOrderLang.siCode") + " : "
            }}{{ scope.row.siCode }}
          </div>
          <div>
            {{ $t("harvestLang.logisticsProducts") + " : "
            }}{{ scope.row.channelName }}
          </div>
          <div>
            {{ $t("statusLang.status") + " : " }}{{ scope.row.orderStatusName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('warehouseEntryLang.providerInfo')"
        min-width="200px"
        align="center"
      >
        <template slot-scope="scope">
          <div>
            {{ $t("harvestLang.providerChannel") + " : "
            }}{{ scope.row.providerChannelName }}
          </div>
          <div>
            {{ $t("warehouseEntryLang.provider") + " : "
            }}{{ scope.row.providerName }}
          </div>
          <div>
            {{ $t("outboundOrderLang.providerNo") + " : "
            }}{{ scope.row.providerTrackingNo }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('outboundOrderLang.goodsInfo')"
        min-width="200px"
        align="center"
      >
        <template slot-scope="scope">
          <div v-for="(item, i) in scope.row.goodsList" :key="i">
            {{
              `${item.goodsSkuCode}[${item.goodsName}]*${item.goodsQuantity}`
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('outboundOrderLang.recipient')"
        min-width="200px"
        align="center"
        prop="receiveName"
      />
      <el-table-column
        :label="$t('goodsSKULang.customerCodeAndName')"
        min-width="200px"
        align="center"
      >
        <template slot-scope="scope">
          <div>
            {{ `${scope.row.customerCode}【${scope.row.customerName}】` }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('depotLang.depotCodeAndName')"
        min-width="200px"
        align="center"
      >
        <template slot-scope="scope">
          <div>
            {{ `${scope.row.depotCode}【${scope.row.depotName}】` }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('goodsSKULang.dateInfo')"
        min-width="200px"
        align="center"
      >
        <template slot-scope="scope">
          <div>
            {{ $t("orderDate") + " : " }} {{ `${scope.row.gmtCreated}` }}
          </div>
          <div>
            {{ $t("outboundDate") + " : " }} {{ `${scope.row.outboundTime}` }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('operation')"
        width="200"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="handleOpenInfo(scope.row)">
            {{ $t("info") }}
          </el-button>
          <el-button
            v-if="scope.row.orderStatus === 0 && false"
            type="text"
            @click="handleCancel(scope.row)"
          >
            {{ $t("outboundOrderLang.cancelOrder") }}
          </el-button>
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              {{ $t("outboundOrderLang.moreOperations")
              }}<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.orderStatus !== 99 && false">
                <el-button type="text" @click="handleReceiveInfo(scope.row)">{{
                  $t("outboundOrderLang.modifyRecipientInfo")
                }}</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button type="text" @click="downloadOrderAttachments(scope.row)">{{
                  $t("outboundOrderLang.downloadOrderAttachments")
                }}</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <el-pagination
        :total="total"
        layoout="total,prev,pager,next"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        @current-change="pageNoChange"
      />
    </el-row> -->
    <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <el-pagination
        :total="total"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 50, 100, 200, 1000, 2000, 5000]"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        @current-change="pageNoChange"
        @size-change="handleSizeChange"
      />
    </el-row>
    <el-dialog
      :visible="infoVisible"
      :title="$t('info')"
      width="1400px"
      @close="handleInfoClose"
    >
      <order-base-info
        :info-data="infoData"
        :goods-data="goodsData"
        :log-data="logData"
        :api-data="apiData"
        :customer-fee-data="customerFeeData"
        :provider-fee-data="providerFeeData"
        :images="images"
      />
    </el-dialog>
    <el-dialog
      :visible="receiveVisible"
      :title="$t('outboundOrderLang.modifyRecipientInfo')"
      width="1400px"
      @close="handleReceiveClose"
    >
      <order-receive-info ref="receiveInfo" :receive-data="receiveData" />
      <div slot="footer">
        <el-button
          type="primary"
          :loading="reveiceSubmitLoading"
          @click="handleReceiveSubmit"
        >{{ $t("submit") }}</el-button>
        <el-button @click="handleReceiveClose">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible="orderAttachmentsVisible"
      title="下载订单附件"
      width="400px"
      @close="handleOrderAttachmentsClose"
    >
      <div class="m-info" style="margin-left: 20px;">
        <el-row :gutter="10" style="margin-bottom: 10px;">
          <el-col
            :span="20"
          >运单面单附件：<span style="color: blue; cursor: pointer;" @click.prevent="download(outBoundUrl)">{{ outBoundAttachments }}</span></el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col
            :span="20"
          >物流商面单附件：<span style="color: blue; cursor: pointer;" @click.prevent="download(trackingUrl)">{{ trackingAttachments }}</span></el-col>
        </el-row>
      </div>
      <div v-show="false" slot="footer">
        <el-button
          type="primary"
          :loading="reveiceSubmitLoading"
          @click="handleOrderAttachmentsClose"
        >{{ $t("submit") }}</el-button>
        <el-button @click="handleOrderAttachmentsClose">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { orderStatusDict, depotOperationStatusDict } from '@/utils/dictData'
import { getDictOptionList } from '@/utils/dictUtils'
import { getDepotList } from '@/api/business/depotManage/depot'
import {
  getOutboundOrderAmountCustomer,
  getOutboundOrderAmountProvider,
  getOutboundOrderGoodsInfo,
  getOutboundOrderInfo,
  getOutboundOrderStatusLog,
  modifyOutboundOrderReceive,
  queryOutboundOrderPageList,
  setOrderStatusCancel,
  downloadFile,
  getChannels,
  getImportOrderList, getOutboundOrderPicture
} from '@/api/business/outboundManage/outboundOrder'
import { getCustomerNameList } from '@/api/business/inventoryManage/inventory';
import OrderBaseInfo from '@/views/business/outboundManage/outboundOrder/components/order-base-info.vue'
import OrderReceiveInfo from '@/views/business/outboundManage/outboundOrder/components/order-receive-info.vue'
import axios from 'axios'
import XLSX from 'xlsx';
export default {
  name: 'OutboundOrder',
  components: { OrderReceiveInfo, OrderBaseInfo },
  data() {
    return {
      statusType: 1,
      noType: 0,
      timeType: 0,
      timeRange: [],
      provideChannelList: [],
      anyNo: undefined,
      orderStatusOptions: getDictOptionList(orderStatusDict),
      depotOperationStatusOptions: getDictOptionList(depotOperationStatusDict),
      customerOptionList: [],
      depotOptions: undefined,
      queryParams: {
        orderStatus: undefined,
        orderNo: undefined,
        trackingNo: undefined,
        siCode: undefined,
        providerTrackingNo: undefined,
        depotId: undefined,
        gmtCreatedStart: undefined,
        gmtCreatedEnd: undefined,
        outboundTimeStart: undefined,
        outboundTimeEnd: undefined,
        receiveTimeStart: undefined,
        receiveTimeEnd: undefined,
        channelName: undefined,
        channelId: undefined,
        selectedChannelId: undefined,
        providerChannelId: undefined,
        customerId: undefined,
        skuCode: undefined,
        pageSize: 10,
        pageNo: 1
      },
      data: [],
      total: 0,
      loading: true,
      infoVisible: false,
      receiveVisible: false,
      reveiceSubmitLoading: false,
      receiveData: {},
      infoData: {},
      goodsData: [],
      logData: [],
      apiData: [],
      customerFeeData: [],
      providerFeeData: [],
      images: [],
      orderAttachmentsVisible: false,
      outBoundAttachments: '',
      trackingAttachments: '',
      outBoundUrl: '',
      trackingUrl: '',
      orderList: {},
      orderLogList: []
    }
  },
  activated() {
    if (this.setSiCode()) {
      this.getList();
    }
  },
  created() {
    this.setSiCode()
    this.getDepotOptions()
    this.getList()
    this.getChannelList()
    this.getCustomerNameList()
  },
  methods: {
    setSiCode() {
      const siCode = this.$route.query.siCode;
      if (siCode) {
        this.anyNo = siCode;
        this.noType = 1;
        this.$router.replace({ query: {}});
      }
      return siCode
    },
    async getDepotOptions() {
      const res = await getDepotList()
      if (!res || res.returnCode !== 10000 || !res.data) return
      this.depotOptions = res.data
    },
    handleSizeChange(pageSize) {
      console.log(pageSize);
      this.queryParams.pageSize = pageSize
      this.queryParams.pageNo = 1
      this.getList()
    },
    async getList() {
      this.loading = true
      const timeRange = this.timeRange || 0
      this.queryParams.gmtCreatedStart = undefined
      this.queryParams.gmtCreatedEnd = undefined
      this.queryParams.outboundTimeStart = undefined
      this.queryParams.outboundTimeEnd = undefined
      this.queryParams.receiveTimeStart = undefined
      this.queryParams.receiveTimeEnd = undefined
      if (this.timeType === 0) {
        this.queryParams.gmtCreatedStart = timeRange[0]
        this.queryParams.gmtCreatedEnd = timeRange[1]
      }
      if (this.timeType === 1) {
        this.queryParams.outboundTimeStart = timeRange[0]
        this.queryParams.outboundTimeEnd = timeRange[1]
      }
      if (this.timeType === 2) {
        this.queryParams.receiveTimeStart = timeRange[0]
        this.queryParams.receiveTimeEnd = timeRange[1]
      }
      const anyNo = this.anyNo?.replace(/\n/g, ' ')
      this.queryParams.orderNo = undefined
      this.queryParams.siCode = undefined
      this.queryParams.providerTrackingNo = undefined
      this.queryParams.trackingNo = undefined
      if (this.noType === 0) {
        this.queryParams.orderNo = anyNo
      }
      if (this.noType === 1) {
        this.queryParams.siCode = anyNo
      }
      if (this.noType === 2) {
        this.queryParams.providerTrackingNo = anyNo
      }
      if (this.noType === 3) {
        this.queryParams.trackingNo = anyNo
      }
      const res = await queryOutboundOrderPageList({
        ...this.queryParams
      })
      this.loading = false
      if (!res || res.returnCode !== 10000 || !res.data) return
      this.data = res.data.dataList
      this.total = res.data.totalRowNum
    },
    pageNoChange(newPageNo) {
      console.log(newPageNo);
      this.queryParams.pageNo = newPageNo
      this.getList()
    },
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    handleReset() {
      this.$refs['queryParams'].resetFields()
      this.timeRange = undefined
      this.anyNo = undefined
      this.queryParams = {
        orderStatus: undefined,
        orderNo: undefined,
        siCode: undefined,
        providerTrackingNo: undefined,
        depotId: undefined,
        gmtCreatedStart: undefined,
        gmtCreatedEnd: undefined,
        outboundTimeStart: undefined,
        outboundTimeEnd: undefined,
        receiveTimeStart: undefined,
        receiveTimeEnd: undefined,
        pageSize: 10,
        pageNo: 1
      }
      this.getList()
    },
    async handleCancel(row) {
      const flag = await this.$confirm(
        this.$t('cancel') + '?',
        this.$t('hint'),
        {
          type: 'warning'
        }
      ).catch((err) => err)
      if (flag === 'cancel') return
      const res = await setOrderStatusCancel({
        orderId: row.orderId
      })
      if (!res || res.returnCode !== 10000) return
      this.$message.success({
        message: this.$t('handleSuccess')
      })
    },
    handleOpenInfo(row) {
      getOutboundOrderInfo({
        orderId: row.orderId
      }).then((res) => {
        if (!res || res.returnCode !== 10000 || !res.data) return
        this.infoData = res.data
        getOutboundOrderGoodsInfo({
          orderId: row.orderId
        }).then((res) => {
          this.goodsData = res.data
        })
        getOutboundOrderStatusLog({
          orderId: row.orderId
        }).then((res) => {
          this.logData = res.data
        })
        getOutboundOrderAmountCustomer({
          orderId: row.orderId
        }).then((res) => {
          this.customerFeeData = res.data
        })
        getOutboundOrderAmountProvider({
          orderId: row.orderId
        }).then((res) => {
          this.providerFeeData = res.data
        })
        getOutboundOrderPicture({
          orderId: row.orderId
        }).then((res) => {
          this.images = res.data.map(item => item.pictureUrl)
        })
        this.infoVisible = true
      })
    },
    handleReceiveInfo(row) {
      getOutboundOrderInfo({
        orderId: row.orderId
      }).then((res) => {
        if (!res || res.returnCode !== 10000 || !res.data) return
        this.receiveData = res.data
        this.receiveVisible = true
      })
    },
    handleReceiveSubmit() {
      this.$refs['receiveInfo'].$refs['form'].validate((valid) => {
        if (valid) {
          this.reveiceSubmitLoading = true
          modifyOutboundOrderReceive({
            ...this.receiveData
          })
            .then((res) => {
              if (!res || res.returnCode !== 10000) return
              this.$message.success({
                message: this.$t('handleSuccess')
              })
              this.handleReceiveClose()
            })
            .finally(() => {
              this.reveiceSubmitLoading = false
            })
        }
      })
    },
    handleInfoClose() {
      this.infoVisible = false
      this.getList()
    },
    handleReceiveClose() {
      this.$refs['receiveInfo'].$refs['form'].resetFields()
      this.receiveData = {}
      this.receiveVisible = false
      this.getList()
    },
    handleOrderAttachmentsClose() {
      this.orderAttachmentsVisible = false
    },
    downloadOrderAttachments(row) {
      this.orderAttachmentsVisible = true
      downloadFile({
        orderId: row.orderId
      }).then((res) => {
        res?.data?.fileDtoList?.forEach(item => {
          if (item.fileType === 'tracking_no_label') {
            this.trackingAttachments = item.fileUrl?.split('/')?.pop()
            this.trackingUrl = item.fileUrl
          } else if (item.fileType === 'tracking_no_label') {
            this.outBoundAttachments = item.fileUrl?.split('/')?.pop()
            this.outBoundUrl = item.fileUrl
          }
        })
      })
    },
    download(fileUrl) {
      const fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1)

      axios.get(fileUrl, { responseType: 'blob' })
        .then(response => {
          const url = window.URL.createObjectURL(new Blob([response.data]))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          // 移除
          URL.revokeObjectURL(link.href)
        })
        .catch(error => {
          console.error(error)
        })
    },
    getChannelList() {
      getChannels().then(response => {
        this.provideChannelList = response.data;
      });
    },
    // 获取客户名称下拉
    async getCustomerNameList() {
      const { data } = await getCustomerNameList()
      console.log(data)
      this.customerOptionList = data
    },
    // 批量导出
    async exportToExcel() {
      const selectedRows = this.$refs.table.store.states.selection;
      const selectedOrderIds = selectedRows.map(row => row.orderId);
      if (selectedOrderIds.length === 0) {
        this.$message.warning('请选择需要导出的数据')
        return;
      }
      const res = await getImportOrderList(selectedOrderIds)
      // 创建工作簿
      const workbook = XLSX.utils.book_new();
      // 构建表头
      const header = ['出库单号', 'OMS单号 ', '拣货单号', '物流产品', '状态', '物流渠道', '物流商', '物流商单号', '收件人', '客户代码/名称', '仓库代码/名称', '下单日期', '包材', '重量', 'sku', '物品名称', '件数'];
      const dataRows = [];
      // 构建数据
      res.data.forEach(item => {
        const mainDataRow = [
          item.orderNo,
          item.trackingNo,
          item.siCode,
          item.channelName,
          item.orderStatusName,
          item.channelName,
          item.providerCode,
          item.providerTrackingNo,
          item.receiveName,
          item.customerCodeAndName,
          item.depotCodeAndName,
          item.gmtCreatedDate,
          item.packName,
          item.weight
        ];
        item.orderGoodDoList.forEach(good => {
          const extendedRow = [...mainDataRow, good.skuCode, good.goodsName, good.goodsQuantity];
          dataRows.push(extendedRow);
        });
      });
      const worksheet = XLSX.utils.aoa_to_sheet([header, ...dataRows]);
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
      const columnWidths = {};
      worksheet['!cols'] = [];
      header.forEach((colName, colIndex) => {
        const maxLength = dataRows.reduce((max, row) => Math.max(max, (row[colIndex] || '').toString().length), 0);
        columnWidths[colIndex] = maxLength < 10 ? 10 : maxLength;
        worksheet['!cols'].push({ wch: columnWidths[colIndex] });
      });

      const excelData = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
      const blob = new Blob([new Uint8Array([...excelData].map(c => c.charCodeAt(0)))], { type: 'application/octet-stream' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = '出库单详情.xlsx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    },
  }
}
</script>

<style lang="scss" scoped>
>>> .el-table__row .cell div {
  font-size: 12px;
  line-height: 14px;
  min-height: 14px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 14px;
  margin-left: 10px;
}

.el-icon-arrow-down {
  font-size: 14px;
}
</style>
